package algorithms;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashMap;

import org.apache.commons.configuration.ConfigurationException;

import commons.IntersezioneRating;
import commons.SimilarityItem;
import commons.UserRatingMap;
import config.ConfigManager;
import datamanagers.DataManagerException;
import datamanagers.DatasourceMySql;

public class UUSimilarityAlgorithm extends SimilarityAlgorithm {

	@Override
	public SimilarityItem eval(int UserId1, int UserId2) throws DataManagerException,
			NumberFormatException, ConfigurationException {
		try {
			HashMap<Integer, Float> medie = (HashMap<Integer, Float>) datamanager
					.getMappaMediaUser();
			Object[] utenti_array = medie.keySet().toArray();

			IntersezioneRating intersezione = datamanager
					.getIntersezioneRating(UserId1, UserId2);

			float[] ratings1 = intersezione.getRatings1();
			float[] ratings2 = intersezione.getRatings2();
			float media1 = medie.get(UserId1);
			float media2 = medie.get(UserId2);
			int i = 0;
			int j = 1;
			SimilarityItem uusim = new SimilarityItem();
			uusim.id1 = UserId1;
			uusim.id2 = UserId2;
			float den, num_sum1, num_sum2;
			den = 0;
			num_sum1 = 0;
			num_sum2 = 0;
			while (i < ratings1.length) {
				den += (ratings1[i] - media1) * (ratings2[i] - media2);
				num_sum1 += Math.pow(ratings1[i] - media1, 2);
				num_sum2 += Math.pow(ratings2[i] - media2, 2);
				i++;
			}
			if (num_sum1 != 0 && num_sum2 != 0) {
				uusim.similarity = (float)(den / (float)Math.sqrt(num_sum1 * num_sum2));
			}
			return uusim;
		} catch (Exception e) {
			throw new DataManagerException(e);
		}
	}

}
